﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using EnvDTE;

namespace devtm.AutoMapper.CustomCode.Helpers
{
    
    public static class GoToDefinition
    {


        public static void NavigateToSourceLocation(this Microsoft.RestrictedUsage.CSharp.Semantics.CSharpMember type)
        {

            foreach (var location in type.SourceLocations)
            {
                location.FileName.Value.NavigateToSourceLocation(location.Position.Line, location.Position.Character);
                return;
            }

        }

        public static void NavigateToSourceLocation(this Microsoft.RestrictedUsage.CSharp.Semantics.CSharpType type)
        {

            foreach (var location in type.SourceLocations)
            {
                location.FileName.Value.NavigateToSourceLocation(location.Position.Line, location.Position.Character);
                return;
            }

        }

        public static void NavigateToSourceLocation(this string fileName, int line, int column)
        {

            IVsUIHierarchy hierarchy;
            uint num;
            IVsWindowFrame frame;
            Guid empty = Guid.Empty;

            try
            {

                VsShellUtilities.OpenDocument(ServiceProvider.GlobalProvider, fileName, empty, out hierarchy, out num, out frame);
                if (frame != null)
                {
                    Window windowObject = VsShellUtilities.GetWindowObject(frame);
                    if (windowObject != null)
                    {
                        TextSelection selection = windowObject.Selection as TextSelection;
                        if (selection != null)
                        {
                            selection.MoveToLineAndOffset(line + 1, column + 1, false);
                            windowObject.Activate();
                        }
                    }
                }

            }
            catch (Exception)
            {

                throw;
            }

            frame = null;
            hierarchy = null;
        }



    }
}
